<template>
  <div class="chart-video">
    <div v-if="!show" class="play-button">
      <div class="button">
        <LoadingOutlined style="font-size: 60px; display: flex; justify-content: center; align-items: center; font-weight: 700" />
      </div>
    </div>
    <div v-else class="chart-video-player vjs-big-play-centered" :id="id"></div>
  </div>
</template>

<script>
  import videojs from 'video.js';
  import '@videojs/http-streaming';
  import 'video.js/dist/video-js.css';

  const startTime = 0;
  const endTime = 100;

  export default {
    props: {
      id: {
        type: String,
        default: 'chart_video_js',
      },
      videoUrl: {
        type: String,
        default: '',
      },
    },
    data() {
      return {
        show: false,
        camList: [],
        currentTime: '00:00',
        endTimeFormatted: this.formatTime(endTime),
        options: {
          autoplay: true, // 设置自动播放
          muted: true, // 设置了它为true，才可实现自动播放,同时视频也被静音 （Chrome66及以上版本，禁止音视频的自动播放）
          controls: true,
          preload: 'auto',
          playbackRates: [0.5, 1, 2], // 支持的播放速率
        },
        player: null,
      };
    },
    methods: {
      // 格式化时间（秒数转换为时:分:秒格式）
      formatTime(seconds) {
        const date = new Date(seconds * 1000);
        const hours = date.getUTCHours();
        const minutes = date.getUTCMinutes();
        const secs = date.getUTCSeconds();
        return `${hours > 0 ? `${hours}:` : ''}${minutes < 10 ? '0' : ''}${minutes}:${secs < 10 ? '0' : ''}${secs}`;
      },
      // 更新时间
      updateTime() {
        const current = this.player.currentTime();
        this.currentTime = this.formatTime(current); // 更新当前时间
      },
      end() {
        console.log('销毁');
        this.show = false;
        if (this.player) {
          this.player.dispose();
        }
        this.player = null;
      },
      // 初始化视频
      getVideo(nowPlayVideoId = `dom_${this.id}`) {
        if (!this.videoUrl) return;
        let videoDom = document.createElement('video');
        videoDom.setAttribute('id', nowPlayVideoId);
        videoDom.setAttribute('class', 'video-js');
        videoDom.setAttribute('style', 'width: 100%; height: 100%');
        this.show = true;
        this.$nextTick(() => {
          const parentDom = document.getElementById(this.id);
          parentDom.appendChild(videoDom);
          this.$emit('getVideoPlayer', videoDom);
          this.$nextTick(() => {
            this.player = videojs(nowPlayVideoId, this.options);
            // 配置HLS流支持
            let type = 'application/x-mpegURL';
            if (this.videoUrl.indexOf('mp4') > 0) {
              type = 'video/mp4';
            }
            this.player.src([
              {
                src: this.videoUrl,
                type: type,
              },
            ]);

            // 等待播放器准备好之后再设置 currentTime
            this.player.ready(() => {
              // 检查 startTime 是否有效，避免设置无效的时间
              const validStartTime = isFinite(startTime) && startTime >= 0 ? startTime : 0;
              if (validStartTime >= 0) {
                this.player.currentTime(validStartTime);
              }
              // 监听 timeupdate 事件
              // this.player.on('timeupdate', this.updateTime);
            });
          });
        });
      },
    },
    mounted() {
      this.getVideo();
    },
    unmounted() {
      this.end();
    },
    watch: {
      videoUrl(val) {
        if (val) {
          this.getVideo();
        } else {
          this.end();
        }
      },
    },
  };
</script>

<style lang="less" scoped>
  .chart-video {
    width: 100%;
    height: 100%;
    .play-button {
      width: 100%;
      height: 100%;
      background-color: #000;
      position: relative;
      .button {
        background-color: #d5d5d5;
        opacity: 0.2;
        width: 120px;
        height: 80px;
        border-radius: 10px;
        position: absolute;
        top: calc(50% - 40px);
        left: calc(50% - 60px);
        cursor: pointer;
        border: 2px solid #fff;
      }
    }
    .chart-video-player {
      width: 100%;
      height: 100%;
    }
    &:deep .vjs-my-button {
      background-color: #3498db;
      color: white;
      font-size: 16px;
      border: none;
      padding: 10px;
      border-radius: 5px;
    }
  }
</style>
